package main

import (
	"bufio"
	"fmt"
	"net"
	"os"
)

func handleConnection(udpConn net.UDPConn) {
	for {
		buf := make([]byte, 1024)
		//n,_:=udpConn.Read(buf)
		n, addr, err := udpConn.ReadFromUDP(buf)
		if err != nil {
			break
		}
		fmt.Printf("客户端%s 的消息 %s\n", addr, string(buf[:n]))

		fmt.Printf("server send:")
		inputs := bufio.NewReader(os.Stdin)
		data, _ := inputs.ReadString('\n')
		//var data string
		//fmt.Scan(&data)
		//w, err := udpConn.Write([]byte(data))  //这个再发送是报错
		w, err := udpConn.WriteToUDP([]byte(data), addr)
		if err != nil {
			fmt.Println("write error", err)
		}
		fmt.Println("发送字节数", w)
	}

}

func main() {
	addr, err := net.ResolveUDPAddr("udp", "127.0.0.1:8000")  //解析地址
	if err != nil {
		fmt.Println(err)
	}
	udpConn, err := net.ListenUDP("udp", addr)
	if err != nil {
		fmt.Println(err)
	}
	//fmt.Println("连接来自：", udpConn.RemoteAddr().String())
	defer udpConn.Close()

	for {
	//	go handleConnection(udpConn)
	handleConnection(*udpConn)
	}
}
